package com.example.base.fragment;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.base.adapter.MyQuestionAdapter;
import com.example.base.adapter.RecyclerViewAdapter;
import com.example.base.bean.Question;
import com.example.base.bean.QuestionThree;
import com.example.base.R;
import com.example.base.activity.WebViewActivity;
import com.example.base.sqllite.MySQLite;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class QuestionFragment extends Fragment {
  private List<QuestionThree> dataList = new ArrayList<>();
  private Context context;
  private RecyclerView recyclerView;
  private RecyclerViewAdapter recyclerAdapter;

  public QuestionFragment() {
  }


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    View inflate = inflater.inflate(R.layout.fragment_question, container, false);
    getDataFromNet();
    initView(inflate);
    initQuestionView();
    return inflate;
  }


  private void initView(View inflate) {
    recyclerView = inflate.findViewById(R.id.recycler_ques);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
    recyclerView.setLayoutManager(linearLayoutManager);
    context = getContext();
  }

  private void getDataFromNet() {
    sendRequestWithokhttp();
  }

  private void sendRequestWithokhttp() {
    OkHttpClient mOkHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
        .url("https://wanandroid.com/wenda/list/1/json")
        .get()
        .build();
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {
      @Override
      public void onFailure(@NotNull Call call, @NotNull IOException e) {
      }

      @Override
      public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        if (response.isSuccessful()) {
          Gson gson = new Gson();
          Question question = gson.fromJson(response.body().string(), Question.class);
          getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
              refreshListView(question);
              recyclerAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
                @Override
                public void onClick(int position) {
                  List<QuestionThree> dataList = recyclerAdapter.getMdataList();
                  MySQLite user = new MySQLite(context, "user", null, 1);
                  SQLiteDatabase db = user.getWritableDatabase();
                  ContentValues cv = new ContentValues();
                  cv.put("title", dataList.get(position).getAuthor());
                  cv.put("text", dataList.get(position).getTitle());
                  cv.put("link", dataList.get(position).getLink());
                  SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  cv.put("time", s.format(new Date()));
                  db.insert("history", null, cv);
                  db.close();
                  Intent intent = new Intent(context, WebViewActivity.class);
                  intent.putExtra("Url", question.getData().getDatas().get(position).getLink());
                  startActivity(intent);
                }
              });
            }
          });
        }
      }
    });
  }

  private void refreshListView(Question question) {
    List<QuestionThree> data = question.getData().getDatas();
    recyclerAdapter.setData(data);
    recyclerAdapter.notifyDataSetChanged();
  }

  private void initQuestionView() {
    recyclerAdapter = new RecyclerViewAdapter(context, dataList);
    recyclerView.setAdapter(recyclerAdapter);
  }
}